package com.fact.actions;

import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.fact.dto.UserDTO;
import com.fact.models.UserService;
import com.opensymphony.xwork2.ActionContext;

public class CheckValidity extends BaseAction implements SessionAware{


	private static final long serialVersionUID = -3942507757291865362L;
	private static final String failedResult="failed";
	private static final String successResult="authenticated";

	
	private String userId;
	private String password;
	private Map<String,Object> session;
	private UserService userService;

	
	public String execute()
	{
		HttpServletResponse response = ServletActionContext.getResponse();
		String resp="failure";
		if(this.isPostRequest() && getUserId()!=null && getPassword()!=null)
		{
			userService=new UserService();
			UserDTO user=userService.validateLogin(getUserId(), getPassword());
			
			if(user!=null)
			{
				if(session instanceof SessionMap)
				{
					((SessionMap<String,Object>)session).invalidate();
					this.session=ActionContext.getContext().getSession();
				}
				this.session.put("authenticated", new Boolean(true));
				this.session.put("user", user);
				this.session.put("role", user.getUserTypeName().toLowerCase());
							
				resp="success";
			}
		}

		try{
        	response.setContentType("text/xml");
        	response.setHeader("Cache-Control", "no-cache");
        	response.getWriter().write(resp);
        	response.flushBuffer();
          }
        catch(Exception e) {e.printStackTrace();}
		
		
		return null;
	}
	
	
	
	
	
	public String getUserId() {
		return userId;
	}
	public void setUserId(String userId) {
		this.userId = userId;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	public Map getSession() {
		return session;
	}
	public void setSession(Map session) {
		this.session = session;
	}

}
